// pages/buy/myOrder_v2/myOrder_v2.js
// import Dialog from '../../../../dist/dialog/dialog';
// var WxParse = require('../../../../wxParse/wxParse.js');
import util from '../../../../utils/util.js';
var app = getApp();
var location = require("../../../../mybehaviors/location/location");

Page({
  behaviors: [location],

  /**
   * 页面的初始数据
   */
  data: {
    //不同购买方式
    options: {}, //路由参数购买方式
    _root_tag: '',
    TAG_ACTION_BUY: "-2", //直接购买
    TAG_ACTION_CART: "-1", //-1购物车结算
    _goodsId: '',
    _optionsId: '',
    _total: 1,
    _cart_ids: [],
    _packagJson: {},
    currentAddId: '',
    currentAddress: {},
    //O2O部分
    store_id: 0,
    selectedMode: 0,
    selected: 0,
    dispatch: [],
    storeCarts: [],
    store_info: {},
    linkinfo: {
      mobile: '',
      name: '',
    },
    //优惠券标识
    cup_notice: true,
    create: true,
    dispatchName: {
      1: '快递',
      2: '上门自提',
      3: '送货上门',
    },
    popupSpecs: false,
    addressData: [],
    defaultAddress: {},
    realname: "", //收件人
    mobile: "",
    address: "",
    order_data: "",
    dispatch_price: 0,
    goods_price: 0,
    price: 0,
    discount_price: 0,
    deduction_price: 0,
    goodsInfo: {},
    //优惠券
    popupCouponSpecs: false,
    checkCouponList: [],
    coupon_size: 0,
    use_coupon_size: 0,
    coupons: [],
    //积分抵扣 其他抵扣
    checkDeductionList: [],
    //新增地址v2------------------------------------------------新增地址v2//
    form: {
      username: '',
      mobile: '',
      province: '',
      city: '',
      district: '',
      street: '',
      address: '',
      isDefault: false,
    },
    addressName: "",
    districtVal: '',
    popAddAddress: false,
    strShow: false, //街道显示
    openDateLw: false,
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    streetShow: false, //街道pop
    //新增地址v2------------------------------------------------新增地址v2//
    //个人信息和修改
    myRealname: "",
    myIdcard: "",
    showMyinfo: false,
    //
    currentIndex: "999",
    //是否开启会员权益开关
    isOpenRight: false,
    //是否选择权益商品
    isRightChoose: false,
    //租赁商品标识
    isRent: false,
    //租期
    rentTime: [],
    //可以免租的件数
    rentFree: "",
    //免押件数
    rent_deposit_free: 0,
    //租赁协议
    agreeCon: {},
    //免租件数
    rent_free: 0,
    rentShow: false,
    tenancy: '',
    //留言
    note: {},
    //跨境
    isTaxGoods: false,
    member_name: '',
    member_card: '',
    explain_title: '',
    explain_content: '',
    //同意租赁协议
    agreement: false,
    agreementShow: false,
    submit_active: true,
    //是否显示支付协议
    AgreementPay: "",
    //同意支付协议
    agreementPay: false,
    //支付协议
    agreementPayShow: false,
    show_address: true,
    // 发票
    isShowInvoice: true,
    invoice_status: true,
    papery_status: "",
    electron_status: "",
    person_status: true,
    unit_status: false,
    iscur: true,
    iscur_b: false,
    iscur_c: true,
    iscur_d: false,
    invoice_list: {
      call: "",
      company_number: ""
    },
    total_items: [],
    discount_amount_items: [],
    //服务费
    service: {},
    isCash: '',
    goodsId: '',
    show1: false,
    pdOrderType: [{
      name: "自用",
      code: "1"
    }], //pending_order_type使用类型：0：零售 1：自用
    POChooseType: "0",
    isOpenTeam: false, //是否为一键开团
    isJoinTeam: false, //是否为去参团
    opren: true,
    is_open_package_deliver: false,
    selfCarryType: [{
      name: "快递",
      dispatch_type_id: 1
    },
    {
      name: "自提",
      dispatch_type_id: 8
    }
    ],
    selfCarrySelected: 0,
    point:{
      lat:'',
      lng:''
    },
    city:'',
    defaultSelfCarry:{},
    package_deliver_id: '1'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //不同购买方式
    this.setData({
      options: options
    });
    let isOpenTeam = !app._isTextEmpty(options.level_id);
    this.setData({
      isOpenTeam
    });

    //是否为一键开团
    let isJoinTeam = !app._isTextEmpty(options.team_id);
    this.setData({
      isJoinTeam
    });

    //是否为去参团
    if (options.tag) {
      this.setData({
        _root_tag: options.tag
      });
    }
    if (wx.getStorageSync("yz_basic_info").globalParameter.is_open_package_deliver == '1') {
      console.log("开启自提点（杨朗）");
      if (options.changeSelfCarry){
        let changeSelfCarry = JSON.parse(options.changeSelfCarry);
        this.setData({
          defaultSelfCarry: changeSelfCarry,
          selfCarrySelected: 1,
          package_deliver_id: 8
        });
      }else{
        this._getLocation(() => { this.getList();});
      }
      this.setData({
        is_open_package_deliver: true
      });
    }
    if (this.data._root_tag == this.data.TAG_ACTION_BUY ||this.data._root_tag == "auction") {
      this.setData({
        _goodsId: options.goodsId,
        _optionsId: options.optionsId,
        _total: options.total
      });
      this._getDataActionBuy(); //直接购买
    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      this.setData({
        _cart_ids: options.cart_ids ? JSON.parse(options.cart_ids) : [],
      });
      this._getDataActionCart(); //购物车结算
    } else if (this.data._root_tag == 'store') {
      this.setData({
        store_id: options.store_id,
        isCash: options.isCash
      });
      if (this.data.isCash === 1) {
        this.getCashGood();
      } else {
        this._initStore();
      }
    } else if (this.data._root_tag == "rentCartBuy") {
      //租赁购物车
      this.setData({
        currentIndex: '999',
        _cart_ids: options.cart_ids ? JSON.parse(options.cart_ids) : [],
        isRent: true
      });
      this._getRentDataActionCart([], []);
      this._getRentTimeList();
      this._judgeIsRight();
    } else if (this.data._root_tag == "rentBuy") {
      this.setData({
        currentIndex: '999',
        isRent: true,
        _goodsId: options.goodsId,
        _optionsId: options.optionsId,
        _total: options.total
      });
      this._getRentDataActionCart([], []);
      this._getRentTimeList();
      this._judgeIsRight();
    } else if (this.data._root_tag == "packagBuy") { //套餐购买
      this.setData({
        _packagJson: options.packagJson,
        _cart_ids: options.cart_ids
      });
      // this.goPackagBuy()
    } else if (this.data._root_tag == "POrder") {
      this.checktag();
      this.setData({
        _goodsId: options.goodsId,
        _optionsId: options.optionsId,
        _total: options.total,
      });
      this._getDataActionBuy();
    } else if (this.data._root_tag == "fromExchange") {
      //会员中心-兑换中心-去兑换（商城商品）
      this.setData({
        _goodsId: options.goodsId
      });
      this.getExchangeData();
    }
    this.getParams();
    // this.getAgreementPay();
    // this._checkTaxGoods();
    // this.getIvoice()
    //加载地址数据初始化
    this._initAddressInfo();
  },
  _checkTaxGoods(data) {
    if (data.status) {
      //显示个人信息
      this.setData({
        showMyinfo: data.status
      });
      this.data.isTaxGoods = true;
    } else {
      this.data.isTaxGoods = false;
      this.setData({
        showMyinfo: false
      });
      //隐藏个人信息
    }
  },
  swichTabTItem(e) {
    console.log(e.detail.index);
    this.setData({
      POChooseType: e.detail.index
    });
  },
  _getMemberInfo(data) {
    this.setData({
      member_name: data.realname,
      member_card: data.idcard,
      myRealname: data.realname,
      myIdcard: data.idcard
    });
  },
  _getExplain(data) {
    this.data.explain_title = data.explain_title;
    this.data.explain_content = data.explain_content;
  },
  //保税真实信息添加
  alertMyInfo() {
    wx.navigateTo({
      url: "/packageB/member/address/myinfo/myinfo?tag=delta"
    });
  },
  gotochangeSelfCarry(){
    //更换自提点
    let that = this;
    wx.navigateTo({
      url: '/packageC/selfCarry/selfCarry_info/selfCarry_info?tag=' + that.data.options.tag + '&goodsId=' + that.data.options.goodsId +
        '&optionsId=' + that.data.options.optionsId + '&total=' + that.data.options.total +'&goods='+ JSON.stringify(this._assembleGoods())
    });
  },
  checktag() {
    console.log('檢查tag');

    let that = this;
    var urlStr = app.getNetAddresss('plugin.pending-order.frontend.wholesale-area.index');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          that.setData({
            activity: res.data.activity,
            activity_time: res.data.activity.end_time
          });
          var nowTime = Date.parse(util.formatTime(new Date()));
          var setTime = Date.parse(that.data.activity_time.replace(/-/g, '/'));
          if (nowTime > setTime) {
            that.setData({
              isfot: false
            });
          } else {
            that.setData({
              isfot: true
            });
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  setDispatch(e) {
    let title = e.detail.title;
    if (this.data.dispatchName["1"] === title) {
      this.setData({
        selected: 1
      });
    } else if (this.data.dispatchName["2"] === title) {
      this.setData({
        selected: 2
      });
    } else if (this.data.dispatchName["3"] === title) {
      this.setData({
        selected: 3
      });
    }
    this._getDataActionStoreCart();
  },
  _initStore() {
    var that = this;
    that.setData({
      recipient_name: "",
      recipient_mobile: ""
    });
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-info-by-store-id");
    urlStr += "&store_id=" + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            store_info: res.data,
            dispatch: res.data.dispatch_type,
            selected: res.data.dispatch_type[0],
            recipient_name: res.data.store_carry.name,
            recipient_mobile: res.data.store_carry.number
          });
          that._getDataActionStoreCart();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //门店购物车商品
  _getDataActionStoreCart() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.index");
    urlStr += "&store_id=" + this.data.store_id;
    // that._getStoreInfo();
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            cup_notice: true,
            storeCarts: []
          });
          res.data.forEach(item => {
            let storeCarts = that.data.storeCarts;
            storeCarts.push(item.id);
            that.setData({
              storeCarts: storeCarts
            });
          });
          that._getStoreCartBuy(that.data.storeCarts);
        } else {
          that.setData({
            cup_notice: true
          });
          wx.showToast({
            icon: 'none',
            title: '无商品',
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });

  },
  _getStoreInfo() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-info-by-store-id");
    urlStr += "&store_id=" + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            store_info: res.data,
            dispatch: res.data.dispatch_type
          });
          if (that.data.dispatch.length > 0) {
            if (!that.data.selected) {
              that.setData({
                selected: that.data.dispatch[0],
              });
            }

          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //显示地址pop
  showAddress() {
    //获取收货地址
    this._getAddress();
  },
  //获取收货地址
  _getAddress() {
    this.addressData = [];
    let that = this;
    let urlStr = app.getNetAddresss("member.member-address.index");
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let defaultAddress = res.data;
          defaultAddress = res.data.filter(function(item) {
            return item.isdefault === 1;
          });

          that.setData({
            popupSpecs: true,
            addressData: res.data,
            defaultAddress: defaultAddress
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //设置地址界面
  _setAddressViewData(model) {
    if (model == undefined || model == "" || model == []) {
      return;
    }
    //设置地址id
    this.data.currentAddId = model.id;
    this.data.currentAddress = model;
    this.setData({
      realname: app._isTextEmpty(model.username) ? "" : model.username,
      mobile: app._isTextEmpty(model.mobile) ? "" : model.mobile,
      address: app._isTextEmpty(model.province) ? "" : model.province + " " + model.city + " " + model.district + " " +
        (app._isTextEmpty(model.street) ? "" : model.street + " ") + model.address
    });
  },
  //门店结算
  _getStoreCartBuy(cart_ids) {
    var that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.cart-buy");
    urlStr += "&cart_ids=" + cart_ids;
    urlStr += "&store_id=" + that.data.store_id;
    urlStr += "&dispatch_type_id=" + that.data.selected;
    urlStr += "&member_coupon_ids=" + this._assembleCoupons();
    urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
    urlStr += "&address=" + JSON.stringify(this.data.currentAddress);
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data
          });
          that._setViewData(res.data); //设置界面
          that._setAddressViewData(res.data.dispatch.default_member_address); //设置地址界面
          that._initCoupon(res.data.discount.member_coupons); //设置优惠券信息
          if (that.data.is_open_package_deliver) {
            that.setData({
              selfCarryType: res.data.dispatch.delivery_method
            });
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //组装优惠券json信息
  _assembleCoupons() {
    let coupons = [];
    for (let i = 0; i < this.data.checkCouponList.length; i++) {
      coupons.push(this.data.checkCouponList[i].id);
    }
    return coupons;
  },
  //组装优惠抵扣信息
  _assembleDeduction() {
    let deductions = [];
    for (let i = 0; i < this.data.checkDeductionList.length; i++) {
      deductions.push(this.data.checkDeductionList[i]);
    }
    return deductions;
  },
  //设置界面
  _setViewData(data) {
    console.log(data.fee_items, '服务费');

    console.log(data, '右束支');

    this.setData({
      order_data: data.orders,
      show_address: data.orders[0].need_address,
      price: data.total_price, //设置总价格（合计）
      total_items: data.amount_items,
      discount_amount_items: data.discount_amount_items,
      service: data.orders[0].order_fees
    });
    console.log(this.data.service, '服务费65655656');

    if (this.data._root_tag == 'store' && this.data.price < 0) {
      wx.showToast({
        icon: 'none',
        title: '下单错误',
        duration: 1500
      });
    }
  },
  //初始化优惠券
  _initCoupon(coupon) {
    if (coupon != undefined && coupon != "" && coupon != null) {
      this.setData({
        coupon_size: coupon.length
      });
    }
    let checkCouponList = [];
    coupon.forEach((item, ind) => {
      if (item.checked == true) {
        checkCouponList.push(item);
      }
    });
    this.setData({
      coupons: coupon,
      use_coupon_size: checkCouponList.length
    });
  },
  //提货人输入
  infonamebtn(e) {
    let infoname = e.detail;
    this.setData({
      "linkinfo.name": infoname
    });
  },
  infonameclear() {
    this.setData({
      "linkinfo.name": ''
    });
  },
  infomobileclear() {
    this.setData({
      "linkinfo.mobile": ''
    });
  },
  //提货人手机输入
  infomobilebtn(e) {
    let infomobile = e.detail;
    this.setData({
      "linkinfo.mobile": infomobile
    });

  },
  addresclosebtn: function() {
    this.setData({
      popupSpecs: false
    });
  },
  //选择地址
  selectAddress(e) {
    let item = e.currentTarget.dataset.addr;
    this._setAddressViewData(item); //更新界面 & ID
    this._requestByAddress(); //选择地址后重新计算
    //关闭 地址栏
    this.setData({
      popupSpecs: false
    });
  },
  //选择地址后重新计算数据
  _requestByAddress() {
    //重新计算
    if (this.data._root_tag == this.data.TAG_ACTION_BUY ||this.data.root_tag == "auction") {
      this.setData({
        order_data: ""
      });
      this._getDataActionBuy(); //直接购买
    } else if (this.data._root_tag == 'fromExchange') {
      this.setData({
        order_data: ""
      });
      this.getExchangeData(0); //直接购买
    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      this.setData({
        order_data: ""
      });
      this._getDataActionCart(); //购物车结算
    } else if (this.data._root_tag == 'store') {
      this._getDataActionStoreCart(); //门店结算
    } else if (this.data_root_tag == "rentCartBuy" || this.data._root_tag == "rentBuy") {
      this._rentGoodBuy();
    } else if (this.data._root_tag == "packagBuy") { //套餐购买
      this.setData({
        order_data: ""
      });
      // this.goPackagBuy()
    }
  },
  editAddress() {
    this.setData({
      "form.address_id": this.data.defaultAddress[0].id,
      "form.username": this.data.defaultAddress[0].username,
      "form.mobile": this.data.defaultAddress[0].mobile,
      "form.province": this.data.defaultAddress[0].province,
      "form.city": this.data.defaultAddress[0].city,
      "form.district": this.data.defaultAddress[0].district,
      "form.address": this.data.defaultAddress[0].address,
      "form.street": this.data.defaultAddress[0].street,
      "form.isDefault": this.data.defaultAddress[0].isDefault === 0 ? false : true
    });
    this.setData({
      popupSpecs: false,
      create: false,
      popAddAddress: true,
    });
    this._getStreet(this.data.defaultAddress[0].district_id);
    this.setData({
      addressName: this.data.form.province + " " + this.data.form.city + " " + this.data.form.district

    });

  },
  //关闭增加地址
  popAddressClose() {
    this.setData({
      popAddAddress: false
    });
  },
  //收件人输入绑定
  usernameinp: function(e) {
    let nameval = e.detail.value;
    this.setData({
      "form.username": nameval
    });
  },
  //联系电话输入绑定
  mobileinp: function(e) {
    let mobileval = e.detail.value;
    this.setData({
      "form.mobile": mobileval
    });
  },
  //默认地址开关值绑定
  isDefaultChange: function(e) {
    let isDefault = e.detail;
    this.setData({
      "form.isDefault": isDefault
    });
  },
  //详细地址绑定输入
  addressinp: function(e) {
    let addressval = e.detail.value;
    console.log(addressval);
    this.setData({
      "form.address": addressval
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function() {
    this.setData({
      openDateLw: false
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function() {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function(res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function(res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function(res) {},
          state: true
        });
      }
    });
  },
  // 读取省key
  _getProvinceData: function() {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function() {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function() {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2]
        });
        console.log("over", that.data.selectAddressData);
      }
    });
  },
  //打开地址选择器
  openDateLwtbtn: function() {
    this.setData({
      openDateLw: true
    });
  },
  // 收货地址滚动事件
  bindChange: function(e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2]
    });
    this._initAddressInfo();
  },
  // 确定选择收货地址
  _okAddress: function() {
    let seleData = this.data.selectAddressData;
    this.setData({
      "form.street": "",
      "districtVal": "",
      "addressName": seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name,
      "form.province": seleData[0].name,
      "form.city": seleData[1].name,
      "form.district": seleData[2].name
    });
    this._getStreet(seleData[2].id);
    this._closeDateLw();
  },
  //获取街道
  _getStreet(param) {
    let that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              strShow: true
            });
          } else {
            that.setData({
              strShow: false
            });
          }
        } else {
          that.setData({
            strShow: false
          });
        }
      },
      fail: function(res) {
        that.setData({
          strShow: false
        });
        console.log(res);
      }
    });
  },
  streetChoose() {
    if (app._isTextEmpty(this.data.addressName)) {
      wx.showToast({
        icon: 'none',
        title: '请先选择所在地区',
        duration: 1500
      });
    } else {
      this.setData({
        streetShow: true,
        opren: false
      });
    }
  },
  //关闭选择街道弹窗
  streetClose: function() {
    this.setData({
      streetShow: false,
      opren: true
    });
  },
  //选择街道
  streetConfirm(e) {
    let strname = e.target.dataset.strname;
    this.setData({
      "form.street": strname,
      "streetShow": false,
      opren: true
    });
  },
  //增加地址
  appendAddress(e) {
    let that = this;
    let apptype = e.currentTarget.dataset.apptype;
    if (app._isTextEmpty(this.data.form.username)) {
      wx.showToast({
        icon: 'none',
        title: "请输入收货人姓名",
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.mobile)) {
      wx.showToast({
        icon: 'none',
        title: "请输入联系电话",
        duration: 1500
      });
      return;
    }
    if (!/^[0-9]{1,}$/.test(this.data.form.mobile)) {
      wx.showToast({
        icon: 'none',
        title: "请输入联系电话",
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.addressName)) {
      wx.showToast({
        icon: 'none',
        title: "请选择所在区域",
        duration: 1500
      });
      return;
    }
    if (this.data.strShow && app._isTextEmpty(this.data.form.street)) {
      wx.showToast({
        icon: 'none',
        title: "请选择所在街道",
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.address)) {
      wx.showToast({
        icon: 'none',
        title: "请输入详细地址",
        duration: 1500
      });
      return;
    }
    let json = {};
    if (this.data.strShow) {
      json = {
        username: this.data.form.username,
        mobile: this.data.form.mobile,
        province: this.data.form.province,
        city: this.data.form.city,
        district: this.data.form.district,
        street: this.data.form.street,
        address: this.data.form.address,
        isdefault: this.data.form.isDefault ? 1 : 0,
        address_id: this.data.form.address_id
      };
    } else {
      json = {
        username: this.data.form.username,
        mobile: this.data.form.mobile,
        province: this.data.form.province,
        city: this.data.form.city,
        district: this.data.form.district,
        address: this.data.form.address,
        isdefault: this.data.form.isDefault ? 1 : 0,
        address_id: this.data.form.address_id
      };
    }
    let urlStr = '';
    if (apptype === 'update') {
      urlStr = app.getNetAddresss('member.member-address.update');
    } else {
      urlStr = app.getNetAddresss('member.member-address.store');
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          that.popAddressClose();
          that._setAddressViewData(res.data);
          that._requestByAddress(); //选择地址后重新计算
          that.setData({
            "form.username": '',
            "form.mobile": '',
            "form.province": '',
            "form.city": '',
            "form.district": '',
            "form.street": '',
            "form.address": '',
            "form.isDefault": false,
            addressName: ''
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {

      }
    });
  },
  //跳转到新增地址
  addAddress() {
    //关闭 地址栏
    this.setData({
      popupSpecs: false
    });
    //新增地址 本地处理
    this.showAddAddress();
  },
  //显示增加地址
  showAddAddress() {
    this.setData({
      "form.username": '',
      "form.mobile": '',
      "form.province": '',
      "form.city": '',
      "form.district": '',
      "form.street": '',
      "form.address": '',
      "form.isDefault": false,
      addressName: '',
      popAddAddress: true,
      create: true
    });
  },
  //租赁购物车结算
  _getRentDataActionCart(right, rent) {
    if (this.data._root_tag == "rentCartBuy") {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.lease-toy.api.order.cart-buy");
      urlStr += "&lease_rights=" + right;
      urlStr += "&lease_term=" + rent;
      urlStr += "&cart_ids=" + this.data._cart_ids;
      urlStr += "&member_coupon_ids=" + this._assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
      urlStr += "&address=" + JSON.stringify(this.data.currentAddress);
      urlStr += "&dispatch_type_id=1";
      urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              goodsInfo: res.data,
              cup_notice: true,
            });
            that._setViewData(res.data); //设置界面
            that._setAddressViewData(res.data.dispatch.default_member_address); //设置地址界面
            that._initCoupon(res.data.discount.member_coupons); //设置优惠券信息
            if (that.data.is_open_package_deliver) {
              that.setData({
                selfCarryType: res.data.dispatch.delivery_method
              });
            }
          } else {
            that.setData({
              cup_notice: true,
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    } else if (this.data._root_tag == "rentBuy") {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.lease-toy.api.order.goods-buy");
      urlStr += "&lease_rights=" + right;
      urlStr += "&lease_term=" + rent;
      urlStr += "&goods_id=" + this.data._goodsId;
      urlStr += "&total=" + this.data._total;
      urlStr += "&option_id=" + this.data._optionsId;
      urlStr += "&member_coupon_ids=" + this._assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
      urlStr += "&address=" + JSON.stringify(this.data.currentAddress);
      urlStr += "&dispatch_type_id=1";
      urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              goodsInfo: res.data,
              cup_notice: true,
            });
            that._setViewData(res.data); //设置界面
            that._setAddressViewData(res.data.dispatch.default_member_address); //设置地址界面
            that._initCoupon(res.data.discount.member_coupons); //设置优惠券信息
            if (that.data.is_open_package_deliver) {
              that.setData({
                selfCarryType: res.data.dispatch.delivery_method
              });
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }

  },
  //获取租期列表
  _getRentTimeList() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.lease-toy.api.lease-term.index");
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            rentTime: res.data.list,
            rentFree: res.data.level.rent_free,
            agreeCon: res.data.lease_toy_set,
            rent_deposit_free: res.data.level.deposit_free,
            rent_free: res.data.level.rent_free,
          });
          // let article_1 = that.data.agreeCon.lease_toy_pact ? that.data.agreeCon.lease_toy_pact : '';
          /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
          // WxParse.wxParse('article_1', 'html', article_1, that);
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //判断是否选择权益商品
  _judgeIsRight() {
    if (this.data.isOpenRight) {
      this.setData({
        isRightChoose: false
      });
    } else {
      this.setData({
        isRightChoose: true
      });
    }
  },
  noteHandle(e) {
    let preid = e.target.dataset.preid;
    let item = e.target.dataset.item;
    let val = e.detail.value;
    this.setData({
      ["note." + preid]: val
    });
    // 触发抵扣事件
    if (!item.order_deductions[0]) {
      //临时数据
      let _deductionItem = {};
      let tempDeduction_ids = [];
      if (this.data.checkDeductionList.length > 0) {
        for (let i = 0; i < this.data.checkDeductionList.length; i++) {
          if (this.data.checkDeductionList[i].pre_id == item.pre_id) {
            //先获取回来
            if (app._isTextEmpty(this.data.checkDeductionList[i].deduction_ids)) {
              tempDeduction_ids = [];
            } else {
              tempDeduction_ids = this.data.checkDeductionList[i].deduction_ids;
            }
            let checkDeductionList = this.data.checkDeductionList;
            checkDeductionList.splice(i, 1);
            this.setData({
              checkDeductionList: checkDeductionList
            });
            break;
          }
        }


        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        } else {
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        }

      } else {
        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }

          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        } else {
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        }
      }
    } else {
      this._screenDiscount(item, item.order_deductions[0]);
    }
  },
  //筛选抵扣
  _screenDiscount(item, value) {
    //临时数据
    let _deductionItem = {};
    let tempDeduction_ids = [];
    if (value.checked) {
      //选中添加
      if (this.data.checkDeductionList.length > 0) {
        for (let i = 0; i < this.data.checkDeductionList.length; i++) {
          if (this.data.checkDeductionList[i].pre_id == item.pre_id) {
            //先获取回来
            if (app._isTextEmpty(this.data.checkDeductionList[i].deduction_ids)) {
              tempDeduction_ids = [];
            } else {
              tempDeduction_ids = this.data.checkDeductionList[i].deduction_ids;
            }
            let checkDeductionList = this.data.checkDeductionList;
            checkDeductionList.splice(i, 1);
            this.setData({
              checkDeductionList: checkDeductionList
            });
            break;
          }
        }

        if (tempDeduction_ids.length > 0) {

          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }

          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        } else {

          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });


        }


      } else {

        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }

          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        } else {
          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        }

      }

    } else { //取消选中
      if (this.data.checkDeductionList.length > 0) {
        for (let i = 0; i < this.data.checkDeductionList.length; i++) {
          if (this.data.checkDeductionList[i].pre_id == item.pre_id) {
            //先获取回来
            if (app._isTextEmpty(this.data.checkDeductionList[i].deduction_ids)) {
              tempDeduction_ids = [];
            } else {
              tempDeduction_ids = this.data.checkDeductionList[i].deduction_ids;
            }
            let checkDeductionList = this.data.checkDeductionList;
            checkDeductionList.splice(i, 1);
            this.setData({
              checkDeductionList: checkDeductionList
            });
            break;
          }
        }


        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        } else {
          //tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        }

      } else {
        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }

          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        } else {
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          _deductionItem.note = this.data.note[item.pre_id];
          let checkDeductionList = this.data.checkDeductionList;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        }

      }
    }

  },
  //权益商品选择事件
  rentSelect(e) {
    let isOpenRight = e.detail;
    this.setData({
      isOpenRight: isOpenRight
    });
    //1.判断是否选择权益商品，有则租期按照会员权益日期计算
    this._clearStorage();
    this._judgeIsRight();
    if (this.data.isOpenRight) {
      let arr = [];
      this.data.order_data.forEach(val => {
        val.order.order_goods.forEach(item => {
          console.log(item);
          let obj = {
            goods_id: item.goods_id,
            total: item.total
          };
          arr.push(obj);
        });
      });
      wx.setStorage({
        key: 'rentTimeRight',
        data: JSON.stringify(arr)
      });
      this._getRentDataActionCart(JSON.stringify(arr), []);
    } else if (!this.data.isOpenRight) {
      this.setData({
        currentIndex: "999"
      });
      this._getRentDataActionCart([], []);
    } else {
      return;
    }
  },
  //清除localstorage
  _clearStorage() {
    wx.removeStorage({
      key: 'rentTimeSelf'
    });
    wx.removeStorage({
      key: 'rentTimeChoose'
    });
    wx.removeStorage({
      key: 'rentTimeRight'
    });
  },
  //抵扣选择响应
  discountHandle(e) {
    let dischecked = e.detail;
    let dindex = e.currentTarget.dataset.dindex;
    let orindex = e.currentTarget.dataset.orindex;
    if (Object.prototype.toString.call(this.data.order_data[orindex].order_deductions) == '[object Object]') {
      this.setData({
        ["order_data[" + orindex + "]" + ".order_deductions." + dindex + ".checked"]: dischecked
      });
    } else if (Object.prototype.toString.call(this.data.order_data[orindex].order_deductions) == '[object Array]') {
      this.setData({
        ["order_data[" + orindex + "]" + ".order_deductions[" + dindex + "]checked"]: dischecked
      });
    }
    this._screenDiscount(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    //重新计算
    if (this.data._root_tag == this.data.TAG_ACTION_BUY ||this.data._root_tag == "auction") {
      this._getDataActionBuy(); //直接购买
    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      this._getDataActionCart(); //购物车结算
    } else if (this.data._root_tag == 'fromExchange') {
      this.getExchangeData(0); //兑换中心
    } else if (this.data._root_tag == 'store') {
      this._getDataActionStoreCart(); //门店结算
    } else if (this.data._root_tag == "rentCartBuy" || this.data._root_tag == "rentBuy") {
      this._rentGoodBuy();
    } else if (this.data._root_tag == "packagBuy") { //套餐购买
      // this.goPackagBuy()
    }
  },
  _rentGoodBuy() {
    if (this.data.isOpenRight) {
      let rentTimeRight = "";
      try {
        const value = wx.getStorageSync('rentTimeRight');
        if (value) {
          rentTimeRight = value;
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
      this._getRentDataActionCart(rentTimeRight, []);
    } else {
      if (this.data.currentIndex == "999") {
        let rentTimeSelf = "";
        try {
          const value = wx.getStorageSync('rentTimeSelf');
          if (value) {
            rentTimeSelf = value;
            // Do something with return value
          }
        } catch (e) {
          // Do something when catch error
        }
        if (!app._isTextEmpty(rentTimeSelf)) {
          this.getRentDataActionCart([], rentTimeSelf);
        } else {
          this._getRentDataActionCart([], []);
        }

      } else {
        let rentTimeChoose = "";
        try {
          const value = wx.getStorageSync('rentTimeChoose');
          if (value) {
            rentTimeChoose = value;
            // Do something with return value
          }
        } catch (e) {
          // Do something when catch error
        }
        if (!app._isTextEmpty(rentTimeChoose)) {
          this._getRentDataActionCart([], rentTimeChoose);
        }

      }

    }
  },
  //选择自定义租期
  rentSelfChoose() {
    this._clearStorage();
    this.setData({
      currentIndex: "999"
    });
    this.setData({
      rentShow: true
    });
  },
  rentShowClose(event) {
    if (event.detail === 'confirm') {
      if (app._isTextEmpty(this.data.tenancy)) {
        wx.showToast({
          icon: 'none',
          title: '租期不能为空',
          duration: 1000
        });
        return;
      }
      let obj = {
        days: this.data.tenancy,
        lease_term_id: 0
      };
      wx.setStorage({
        key: 'rentTimeSelf',
        data: JSON.stringify(obj)
      });
      this._getRentDataActionCart([], JSON.stringify(obj));
      // 异步关闭弹窗
      setTimeout(() => {
        this.setData({
          rentShow: false
        });
      }, 1000);
    } else {
      this.setData({
        rentShow: false
      });
      console.log("取消自定义租期！！！");
    }
  },
  //自定义租期数值绑定
  rentShowinp(e) {
    let rentval = e.detail;
    this.setData({
      tenancy: rentval
    });
  },
  //自定义租期值清除
  rentclear() {
    this.setData({
      tenancy: ''
    });
  },
  //选择租期
  rentTimeChoose(e) {
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    if (this.data.currentIndex == index) {
      this.setData({
        currentIndex: "999"
      });
      this._clearStorage();
      this._getRentDataActionCart([], []);
    } else {
      this._clearStorage();
      this.setData({
        currentIndex: index
      });
      let obj = {
        days: 0,
        lease_term_id: item.id
      };
      wx.setStorage({
        key: 'rentTimeChoose',
        data: JSON.stringify(obj)
      });
      this._getRentDataActionCart([], JSON.stringify(obj));
    }
  },
  //购物车结算
  _getDataActionCart() {
    let that = this;
    let urlStr = app.getNetAddresss("order.cart-buy");
    urlStr += "&cart_ids=" + this.data._cart_ids;
    urlStr += "&member_coupon_ids=" + this._assembleCoupons();
    urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
    urlStr += "&address=" + JSON.stringify(this.data.currentAddress);
    urlStr += "&dispatch_type_id=1";
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data,
            cup_notice: true
          });
          that._setViewData(res.data); //设置界面
          that._setAddressViewData(res.data.dispatch.default_member_address); //设置地址界面
          that._initCoupon(res.data.discount.member_coupons); //设置优惠券信息
          if (that.data.is_open_package_deliver) {
            that.setData({
              selfCarryType: res.data.dispatch.delivery_method
            });
          }
        } else {
          that.setData({
            cup_notice: true
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //优惠券
  showCoupon() {
    if (this.data.coupon_size == 0) {
      wx.showToast({
        icon: 'none',
        title: '暂无优惠券使用',
        duration: 1500
      });
      return;
    }
    this.setData({
      popupCouponSpecs: true
    });
  },
  //选择优惠券
  selectCoupon(e) {
    let couponBol = e.detail;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    this.setData({
      ["coupons[" + index + "].checked"]: couponBol
    });
    this._screenCoupon(couponBol, item);
    //设置view
    this._setCouponView();
    //重新计算
    if (this.data._root_tag == this.data.TAG_ACTION_BUY || this.data._root_tag == "auction") {
      this._getDataActionBuy(); //直接购买
    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      this._getDataActionCart(); //购物车结算
    } else if (this.data._root_tag == 'fromExchange') {
      this.getExchangeData(0); //兑换中心
    } else if (this.data._root_tag == 'store') {
      this._getDataActionStoreCart(); //门店结算
    } else if (this.data._root_tag == "rentCartBuy" || this.data._root_tag == "rentBuy") {
      this._rentGoodBuy();
    } else if (this.data._root_tag == "packagBuy") { //套餐购买
      // this.goPackagBuy()
    }
  },
  //筛选数据优惠券状态
  _screenCoupon(couponBol, valObj) {
    var tarValue = valObj;
    if (couponBol) { //选中添加
      this.setData({
        cup_notice: false
      });
      if (this.data.checkCouponList.length > 0) {
        for (let i = 0; i < this.data.checkCouponList.length; i++) {
          if (this.data.checkCouponList[i].id == tarValue.id) {
            let checkCouponList = this.data.checkCouponList;
            checkCouponList.splice(i, 1);
            this.setData({
              checkCouponList: checkCouponList
            });
          }
        }
        let checkCouponList = this.data.checkCouponList;
        checkCouponList.push(tarValue);
        this.setData({
          checkCouponList: checkCouponList
        });
      } else {
        let checkCouponList = this.data.checkCouponList;
        checkCouponList.push(tarValue);
        this.setData({
          checkCouponList: checkCouponList
        });
      }

    } else { //取消选中
      this.setData({
        cup_notice: true
      });
      if (this.data.checkCouponList.length > 0) {
        for (let i = 0; i < this.data.checkCouponList.length; i++) {
          if (this.data.checkCouponList[i].id == tarValue.id) {
            let checkCouponList = this.data.checkCouponList;
            checkCouponList.splice(i, 1);
            this.setData({
              checkCouponList: checkCouponList
            });
          }
        }
      }
    }
  },
  //设置view
  _setCouponView() {
    this.setData({
      use_coupon_size: this.data.checkCouponList.length
    });
  },
  //关闭优惠卷
  couponclose() {
    this.setData({
      popupCouponSpecs: false
    });
  },
  //租赁协议
  agreementbtn(e) {
    let agreeBol = e.detail;
    this.setData({
      agreement: agreeBol
    });
  },
  //租赁弹窗显示
  showAgreement() {
    this.setData({
      agreementShow: true
    });
  },
  agreementClose() {
    this.setData({
      agreementShow: false
    });
  },
  //直接购买
  _getDataActionBuy() {
    let that = this;
    let _URL_DataActionBuy = ''; //  api
    let urlStr = '';
    console.log(this.data._root_tag);
    if (this.data.isOpenTeam) {
      console.log("一键开团，leveid", this.data.isOpenTeam);
      _URL_DataActionBuy =
        "plugin.fight-groups.frontend.controllers.team.pre-open-team";
      urlStr = app.getNetAddresss(_URL_DataActionBuy);
      //规格层级id
      //一键开团 拼团层级id
      urlStr += "&level_id=" + this.options.level_id;
      urlStr += "&option_level_id=" + this.options.option_level_id;
    } else if (this.data.isJoinTeam) {
      console.log("去参团", this.data.isJoinTeam);
      //一键开团 拼团层级id
      //规格层级id
      _URL_DataActionBuy =
        "plugin.fight-groups.frontend.controllers.team.pre-join-team";
      urlStr = app.getNetAddresss(_URL_DataActionBuy);
      //规格层级id
      //一键开团 拼团层级id
      urlStr += "&team_id=" + this.options.team_id;
      urlStr += "&option_level_id=" + this.options.option_level_id;
    } else if (this.data._root_tag == 'POrder') {
      _URL_DataActionBuy = "plugin.pending-order.frontend.goods-buy.index";
      urlStr = app.getNetAddresss(_URL_DataActionBuy);
      urlStr += "&pending_order_type=" + this.data.POChooseType;
    }else if (this.data._root_tag == 'auction') {
      urlStr = app.getNetAddresss('plugin.auction.api.goods-buy');
      urlStr += "&auction_sn=" + this.data.options.auction_sn;
      urlStr += "&fixed_price=" + this.data.options.fixed_price;
    } else {
      _URL_DataActionBuy = "order.goods-buy";
      urlStr = app.getNetAddresss(_URL_DataActionBuy);
    }

    urlStr += "&goods_id=" + this.data._goodsId;
    urlStr += "&total=" + this.data._total;
    urlStr += "&option_id=" + this.data._optionsId;
    urlStr += "&member_coupon_ids=" + this._assembleCoupons();
    urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
    urlStr += "&address=" + JSON.stringify(this.data.currentAddress);
    urlStr += "&dispatch_type_id=1";
    urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data,
            cup_notice: true
          });
          that._setViewData(res.data); //设置界面
          that._setAddressViewData(res.data.dispatch.default_member_address); //设置地址界面
          that._initCoupon(res.data.discount.member_coupons); //设置优惠券信息

          if (that.data.is_open_package_deliver) {
            that.setData({
              selfCarryType: res.data.dispatch.delivery_method
            });
          }
        } else {
          if (that.data._root_tag == 'POrder') {
            that.setData({
              cup_notice: true
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              });
            }, 1000);
          }
          if(that.data._root_tag == 'auction'){
            wx.navigateBack({
              delta:1
            });
          }
          that.setData({
            cup_notice: true
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  getExchangeData(_id) {
    let that = this;
    let urlStr = app.getNetAddresss("coupon.exchange-center.exchange-buy");
    console.log("dkjsakjfaskf", JSON.parse(this.data.options.exchangeData));
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        goods_id: this.data._goodsId,
        total: this.data._total,
        option_id: this.data._optionsId,
        member_coupon_ids: this._assembleCoupons(),
        orders: JSON.stringify(this._assembleDeduction()),
        address: JSON.stringify(this.data.currentAddress),
        dispatch_type_id: 1,
        mark: this.data.options.mark ? this.data.options.mark : 0,
        data: JSON.parse(this.data.options.exchangeData),
        is_exchange: _id == 0 ? 0 : 1
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data,
            cup_notice: true
          });
          that._setViewData(res.data); //设置界面
          that._setAddressViewData(res.data.dispatch.default_member_address); //设置地址界面
          that._initCoupon(res.data.discount.member_coupons); //设置优惠券信息
        } else {
          that.setData({
            cup_notice: true
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res.msg);
      }
    });
  },
  //提交订单
  submit() {
    if (this.data.submit_active == true) {
      this.data.submit_active = false;
      if (this.data.AgreementPay && !this.data.isRent) {
        if (!this.data.agreementPay) {
          wx.showToast({
            icon: 'none',
            title: "请勾选支付协议",
            duration: 1500
          });
          this.data.submit_active = true;
          return;
        }
      }
      if (this.data.is_open_package_deliver && this.data.package_deliver_id == 8){
        if (app._isTextEmpty(this.data.defaultSelfCarry.id)) {
          wx.showModal({
            title: '提示',
            content: '请选择自提点',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#000000',
            success: (res) => {
            },
            fail: function (res) { },
            complete: function (res) { },
          });
          this.data.submit_active = true;
          return;
        }
        if (app._isTextEmpty(this.data.linkinfo.name)) {
          wx.showModal({
            title: '提示',
            content: '请填写提货人姓名',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#000000',
            success: (res) => {
            },
            fail: function (res) { },
            complete: function (res) { },
          });
          this.data.submit_active = true;
          return;
        }
        if (app._isTextEmpty(this.data.linkinfo.mobile)) {
          wx.showModal({
            title: '提示',
            content: '请输入提货人手机',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#000000',
            success: (res) => {
            },
            fail: function (res) { },
            complete: function (res) { },
          });
          this.data.submit_active = true;
          return;
        }
      }
      if (this.data.isRent) {
        if (this.data.store_id) {
          this._submitStore();
          this.data.submit_active = true;
          return;
        }
        if (!this.data.order_data[0].need_address && (this.data.is_open_package_deliver && this.data.package_deliver_id != 8)) {
          if (app._isTextEmpty(this.data.currentAddId)) {
            wx.showModal({
              title: '提示',
              content: '请选择收货地址',
              showCancel: false,
              confirmText: '确定',
              confirmColor: '#000000',
              success: (res) => {
                this.showAddress();
              },
              fail: function(res) {},
              complete: function(res) {},
            });
            this.data.submit_active = true;
            return;
          }
        }

        if (!this.data.agreement) {
          wx.showToast({
            icon: 'none',
            title: "请勾选租赁协议",
            duration: 1500
          });
          this.data.submit_active = true;
          return;
        }

        let that = this;
        let urlStr = "";
        if (this.data._root_tag == 'POrder') {
          urlStr = app.getNetAddresss("plugin.pending-order.frontend.create.index");
          urlStr += "&pending_order_type=" + this.data.POChooseType;
        }else if (this.data._root_tag == "auction") {
          urlStr = app.getNetAddresss("plugin.auction.api.order-create");
          urlStr += "&auction_sn="+ this.data.options.auction_sn;
        } else {
          urlStr = app.getNetAddresss("plugin.lease-toy.api.order.create");
        }

        let json = this._assembleJson();
        app._postNetWork({
          url: urlStr,
          showToastIn: false,
          data: json,
          success: function(resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              that._clearStorage();
              that.data.submit_active = true;
              wx.redirectTo({
                url: '../orderPay/orderPay?order_id=' + res.data.order_ids + '&status=2'
              });
            } else {
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 2000
              });
              that.data.submit_active = true;
            }
          },
          fail: function(res) {
            console.log(res);
          }
        });

      } else {
        if (this.data.store_id) {
          this._submitStore();
          this.data.submit_active = true;
          return;
        }
        if (!this.data.order_data[0].need_address && (!this.data.is_open_package_deliver && this.data.package_deliver_id != '8')) {
          if (app._isTextEmpty(this.data.currentAddId)) {
            wx.showModal({
              title: '提示',
              content: '请选择收货地址',
              showCancel: false,
              confirmText: '确定',
              confirmColor: '#000000',
              success: (res) => {
                this.showAddress();
              },
              fail: function(res) {},
              complete: function(res) {},
            });
            this.data.submit_active = true;
            return;
          }
        }
        // if(!this.data.order_data[0].need_address && !this.data.is_open_package_deliver && this.data.package_deliver_id != '8'){
        //   if (app._isTextEmpty(this.data.currentAddId)){
        //     wx.showModal({
        //       title: '提示',
        //       content: '请选择收货地址',
        //       showCancel: false,
        //       confirmText: '确定',
        //       confirmColor: '#000000',
        //       success: (res) => {
        //         this.showAddress()
        //       },
        //       fail: function (res) { },
        //       complete: function (res) { },
        //     })
        //     this.data.submit_active = true;
        //     return;
        //   }
        // }
        let that = this;
        let json = this._assembleJson();
        let urlStr;
        if (this.data.isOpenTeam || this.data.isJoinTeam) {
          urlStr = app.getNetAddresss("plugin.fight-groups.frontend.controllers.create.index");
        } else if (this.data._root_tag == 'POrder') {
          urlStr = app.getNetAddresss("plugin.pending-order.frontend.create.index");
          urlStr += "&pending_order_type=" + this.data.POChooseType;
          console.log('进porder');
        }else if (this.data._root_tag == "auction") {
          urlStr = app.getNetAddresss("plugin.auction.api.order-create");
          urlStr += "&auction_sn="+ this.data.options.auction_sn;
        } else {
          urlStr = app.getNetAddresss("order.create");
        }

        app._postNetWork({
          url: urlStr,
          showToastIn: false,
          data: json,
          success: function(resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              that.data.submit_active = true;
              if (that.options.option_level_id) {
                wx.redirectTo({
                  url: '../orderPay/orderPay?order_id=' + res.data.order_ids + '&status=2' + '&name=groups'
                });
                return;
              }
              console.log('跳转到订单页');
              wx.redirectTo({
                url: '/packageD/buy/orderPay/orderPay?order_id=' + res.data.order_ids + '&status=2'
              });

            } else {
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 1500
              });
            }
          },
          fail: function(res) {
            console.log(res);
          }
        });

      }

    }

  },
  _submitStore() {

    if (this.data.store_info.delivery_information == null || this.data.store_info.delivery_information == 0) {
      if ((this.data.selected == '1' || this.data.selected == '3') && app._isTextEmpty(this.data.currentAddId)) {
        if (!this.data.order_data[0].need_address && (this.data.is_open_package_deliver && this.data.package_deliver_id != 8)) {
          wx.showModal({
            title: '提示',
            content: '请选择收货地址',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#000000',
            success: (res) => {
              this.showAddress();
            },
            fail: function(res) {},
            complete: function(res) {},
          });
          this.data.submit_active = true;
          return;
        }
      }

      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.create");
      let json = {
        dispatch_type_id: this.data.selected,
        store_id: this.data.store_id,
        mobile: this.data.store_info.store_mobile,
        realname: this.data.store_info.store_name,
        address: JSON.stringify(this.data.currentAddress),
        goods: JSON.stringify(this._assembleGoods()),
        cart_ids: JSON.stringify(this.data.storeCarts),
        member_coupon_ids: JSON.stringify(this._assembleCoupons()),
        orders: JSON.stringify(this._assembleDeduction()),
        invoice_type: (this.data.iscur_c ? 0 : 1),
        rise_type: (this.data.iscur ? 1 : 0),
        call: this.data.invoice_list.call,
        company_number: this.data.invoice_list.company_number
      };
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.redirectTo({
              url: '../orderPay/orderPay?order_id=' + res.data.order_ids + '&status=2'
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });

    } else if (this.data.store_info.delivery_information == 1) {
      if (this.data.selected == '2' && (app._isTextEmpty(this.data.linkinfo.name) || app._isTextEmpty(this.data.linkinfo
        .mobile))) {
        wx.showToast({
          icon: 'none',
          title: "请输入提货人信息",
          duration: 1500
        });
        this.data.submit_active = true;
        return;
      }

      if ((this.data.selected == '1' || this.data.selected == '3') && app._isTextEmpty(this.data.currentAddId)) {
        if (!this.order_data[0].need_address && (this.data.is_open_package_deliver && this.data.package_deliver_id != 8)) {
          wx.showModal({
            title: '提示',
            content: '请选择收货地址',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#000000',
            success: (res) => {
              this.showAddress();
            },
            fail: function(res) {},
            complete: function(res) {},
          });
          this.data.submit_active = true;
          return;
        }
      }

      if (this.selected == '2' && !/^[0-9]{1,}$/.test(this.data.linkinfo.mobile)) {
        wx.showToast({
          icon: 'none',
          title: "请输入正确的联系电话",
          duration: 1500
        });
        this.data.submit_active = true;
        return;
      }

      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.create");
      let json = this._assembleJson();
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.redirectTo({
              url: '../orderPay/orderPay?order_id=' + res.data.order_ids + '&status=2'
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }

  },
  //组装商品信息
  _assembleGoods() {
    let newGoods = [];
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
        let model = new Object();
        model.goods_id = this.data.goodsInfo.orders[j].order_goods[i].goods_id;
        model.total = this.data.goodsInfo.orders[j].order_goods[i].total;
        model.option_id = this.data.goodsInfo.orders[j].order_goods[i].goods_option_id;
        newGoods.push(model);
      }
    }
    return newGoods;
  },
  //组装json数据
  _assembleJson() {
    let json = {};
    if (this.data._root_tag == this.data.TAG_ACTION_BUY || this.data._root_tag == "auction") {
      json = {
        dispatch_type_id: 1,
        address: JSON.stringify(this.data.currentAddress),
        auction_sn:this.data.options.auction_sn,
        fixed_price: '1',
        goods: JSON.stringify(this._assembleGoods()),
        member_coupon_ids: JSON.stringify(this._assembleCoupons()),
        orders: JSON.stringify(this._assembleDeduction()),
        mark: this.data.options.mark ? this.data.options.mark : 0,
        invoice_type: (this.data.iscur_c ? 0 : 1), // 发票
        rise_type: (this.data.iscur ? 1 : 0),
        call: this.data.invoice_list.call,
        company_number: this.data.invoice_list.company_number
      };
      //isOpenTeam 一键开团
      if (this.data.isOpenTeam) {
        json.level_id = this.options.level_id;
        json.option_level_id = this.options.option_level_id;
      } else if (this.data.isJoinTeam) {
        json.team_id = this.options.team_id;
        json.option_level_id = this.options.option_level_id;
      }
    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      json = {
        dispatch_type_id: 1,
        address: JSON.stringify(this.data.currentAddress),
        goods: JSON.stringify(this._assembleGoods()),
        cart_ids: JSON.stringify(this.data._cart_ids),
        member_coupon_ids: JSON.stringify(this._assembleCoupons()),
        orders: JSON.stringify(this._assembleDeduction()),
        invoice_type: (this.data.iscur_c ? 0 : 1), // 发票
        rise_type: (this.data.iscur ? 1 : 0),
        call: this.data.invoice_list.call,
        company_number: this.data.invoice_list.company_number
      };
    } else if (this.data._root_tag == 'store') {
      json = {
        dispatch_type_id: this.data.selected,
        store_id: this.data.store_id,
        mobile: this.data.linkinfo.mobile,
        realname: this.data.linkinfo.name,
        address: JSON.stringify(this.data.currentAddress),
        goods: JSON.stringify(this._assembleGoods()),
        cart_ids: JSON.stringify(this.data.storeCarts),
        member_coupon_ids: JSON.stringify(this._assembleCoupons()),
        orders: JSON.stringify(this._assembleDeduction()),
        invoice_type: (this.data.iscur_c ? 0 : 1), // 发票
        rise_type: (this.data.iscur ? 1 : 0),
        call: this.data.invoice_list.call,
        company_number: this.data.invoice_list.company_number
      };
    } else if (this.data._root_tag == "rentCartBuy" || this.data._root_tag == "rentBuy") {
      let right = "";
      try {
        const value = wx.getStorageSync('rentTimeRight');
        if (value) {
          right = value;
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
      let choose = "";
      try {
        const value = wx.getStorageSync('rentTimeChoose');
        if (value) {
          choose = value;
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
      let self = "";
      try {
        const value = wx.getStorageSync('rentTimeSelf');
        if (value) {
          self = value;
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
      let r = app._isTextEmpty(right) == null ? [] : right;
      let assem = {};
      if (!app._isTextEmpty(choose)) {
        assem = choose;
      } else if (!app._isTextEmpty(self)) {
        assem = self;
      } else {
        assem = {};
      }
      json = {
        lease_rights: r,
        lease_term: assem,
        dispatch_type_id: 1,
        address: JSON.stringify(this.data.currentAddress),
        goods: JSON.stringify(this._assembleGoods()),
        cart_ids: JSON.stringify(this.data._cart_ids),
        member_coupon_ids: JSON.stringify(this._assembleCoupons()),
        orders: JSON.stringify(this._assembleDeduction()),
        mark: this.data.options.mark ? this.data.options.mark : 0,
        invoice_type: (this.data.iscur_c ? 0 : 1), // 发票
        rise_type: (this.data.iscur ? 1 : 0),
        call: this.data.invoice_list.call,
        company_number: this.data.invoice_list.company_number
      };
    } else if (this.data._root_tag == 'POrder') {
      // 挂单
      json = {
        dispatch_type_id: 1,
        address: JSON.stringify(this.data.currentAddress),
        goods: JSON.stringify(this._assembleGoods()),
        member_coupon_ids: JSON.stringify(this._assembleCoupons()),
        orders: JSON.stringify(this._assembleDeduction()),
        mark: this.data.options.mark ? this.data.options.mark : 0,
        // 发票
        invoice_type: (this.data.iscur_c ? 0 : 1), // 发票
        rise_type: (this.data.iscur ? 1 : 0),
        call: this.data.invoice_list.call,
        company_number: this.data.invoice_list.company_number
      };
    } else if (this.data._root_tag == "fromExchange") {
      // 兑换中心
      json = {
        dispatch_type_id: 1,
        address: JSON.stringify(this.data.currentAddress),
        goods: JSON.stringify(this._assembleGoods()),
        member_coupon_ids: JSON.stringify(this._assembleCoupons()),
        orders: JSON.stringify(this._assembleDeduction()),
        mark: this.data.options.mark ? this.data.options.mark : 0,
        // 发票
        invoice_type: (this.data.iscur_c ? 0 : 1), // 发票
        rise_type: (this.data.iscur ? 1 : 0),
        call: this.data.invoice_list.call,
        company_number: this.data.invoice_list.company_number
      };
    }

    if (this.data.is_open_package_deliver && this.data.package_deliver_id == 8){
      json.dispatch_type_id = 8;
      json.package_deliver_id = this.data.defaultSelfCarry.id;
      json.realname = this.data.linkinfo.name;
      json.mobile = this.data.linkinfo.mobile;
      delete json.address;
    }
    return json;
  },
  setDispatchdeliver(e){
    console.log("变化配送方式", e.detail.title);
    let title = e.detail.title;
    if (title == "快递") {
      this.setData({
        package_deliver_id: 1,
        selfCarrySelected: 0
      });
    } else if (title =='上门自提') {
      this.setData({
        package_deliver_id: 8,
        selfCarrySelected: 1
      });
    }
  },
  //获取是否显示支付协议
  getAgreementPay() {
    let that = this;
    let urlStr = app.getNetAddresss("shop.index.getPayProtocol");
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            AgreementPay: res.data ? res.data : ''
          });
          // let article_2 = that.data.AgreementPay ? that.data.AgreementPay : '';
          /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
          // WxParse.wxParse('article_2', 'html', article_2, that);
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //支付协议
  agreementPaybtn(e) {
    let agreeBol = e.detail;
    this.setData({
      agreementPay: agreeBol
    });
  },
  showPay() {
    this.setData({
      agreementPayShow: true
    });
  },
  showPayClose() {
    this.setData({
      agreementPayShow: false
    });
  },
  getIvoice(data) {
    this.setData({
      papery_status: parseInt(data.invoice.papery),
      electron_status: parseInt(data.invoice.electron)
    });
    if (!this.data.papery_status && !this.data.electron_status) {
      this.setData({
        isShowInvoice: false
      });
    }
  },
  //门店过期商品下单
  getCashGood() {
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.enter.getSetGoodsId");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goods_id: res.data.goods_id
          });
          if (!res.data.store) {
            that.setData({
              _goodsId: res.data.goods_id,
              _root_tag: "-2",
              store_id: 0
            });
            that._getDataActionBuy();
          } else {
            that.setData({
              _root_tag: "store"
            });
            that.setData({
              store_info: res.data.store,
              dispatch: res.data.store.dispatch_type
            });
            if (that.data.dispatch.length > 0) {
              if (!that.data.selected) {
                that.setData({
                  selected: that.data.dispatch[0].toString()
                });
              }
            }
            that._getDataActionStoreCart();
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  // 整合了发票、是否显示个人信息接口
  getParams(cart_ids) {
    let json = {};
    let that = this;
    if (this.data._root_tag == "store" && !cart_ids) {
      return;
    } else if (this.data._root_tag == "store" && cart_ids) {
      this.setData({
        _cart_ids: cart_ids
      });
    }
    if (this.data._root_tag == this.data.TAG_ACTION_BUY || this.data._root_tag == 'auction') {
      this.setData({
        _goodsId: this.data.options.goodsId
      });
      let cart_ids = this.data._cart_ids;
      cart_ids.push(this.data._goodsId);
      this.setData({
        _cart_ids: cart_ids
      });
    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      this.setData({
        _cart_ids: this.data.options.cart_ids ? JSON.parse(this.data.options.cart_ids) : []
      });
    } else if (this.data._root_tag == "rentCartBuy") { //加入租赁商品
      this.setData({
        _cart_ids: this.data.options.cart_ids ? JSON.parse(this.data.options.cart_ids) : []
      });
    } else if (this.data._root_tag == "rentBuy") { //加入租赁立即租
      this.setData({
        _goodsId: this.data.options.goodsId
      });
      let cart_ids = this.data._cart_ids;
      cart_ids.push(this.data._goodsId);
      this.setData({
        _cart_ids: cart_ids
      });
    }
    let urlStr = app.getNetAddresss("from.div-from.get-params");
    json = {
      goods_ids: JSON.stringify(this.data._cart_ids)
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isGetAgreementPay: true,
            AgreementPay: res.data.getPayProtocol ? res.data.getPayProtocol : ''
          });
          that._checkTaxGoods(res.data.isDisplay);
          that._getMemberInfo(res.data.getMemberInfo);
          that._getExplain(res.data.explain);
          that.getIvoice(res.data.sinvoice);
        } else {
          that.setData({
            isGetAgreementPay: false
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  show1btn() {
    this.setData({
      show1: true
    });
  },
  closePopup() {
    this.setData({
      show1: false
    });
  },
  invoice_type() {
    if (this.data.iscur_c) {
      this.setData({
        iscur_c: false,
        iscur_d: true
      });
    } else {
      this.setData({
        iscur_c: true,
        iscur_d: false
      });
    }
  },
  invoice_title() {
    // 清空填写
    this.setData({
      'invoice_list.call': "",
      'invoice_list.company_number': ''
    });
    if (this.data.iscur) {
      this.setData({
        iscur: false,
        iscur_b: true,
        person_status: false,
        unit_status: true
      });
    } else {
      this.setData({
        iscur: true,
        iscur_b: false,
        person_status: true,
        unit_status: false
      });
    }
  },
  Subinvoice() {
    if (app._isTextEmpty(this.data.invoice_list.call)) {
      wx.showToast({
        title: '请填写抬头',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    if (
      this.data.iscur_b &&
      app._isTextEmpty(this.data.invoice_list.company_number)
    ) {
      wx.showToast({
        title: '请添加纳税人识别号',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    // 页面回显
    this.setData({
      invoicename: this.data.iscur_c ? "电子" : "纸质",
      companyname: this.data.iscur ? "个人" : "单位",
      showInvoiceTitle: this.data.invoice_list.call,
      show1: false
    });
  },
  callinp(e) {
    let val = e.detail.value;
    this.setData({
      'invoice_list.call': val
    });
  },
  companyNumberinp(e) {
    let val = e.detail.value;
    this.setData({
      'invoice_list.company_number': val
    });
  },

  getList(){
    let that = this;
    let urlStr = app.getNetAddresss("plugin.package-deliver.frontend.deliver.getList");
    app._getNetWork({
      url: urlStr,
      data: {
        city_name: that.data.city,
        lat: that.data.point.lat,
        lng: that.data.point.lng,
        kwd: ""
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            defaultSelfCarry: res.data.list.data[0] ? res.data.list.data[0]: "",
            package_deliver_id: res.data.list.data[0].dispatch_type_id
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: '获取自提点失败',
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  }
});
